package com.ruizhong.remotehelper;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.List;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

public class mainActivity extends AppCompatActivity {

    private static DatagramSocket client;

    private static String BROADCAST_IP = "255.255.255.255";

    public static List<String> deviceList = new ArrayList<>();

    private String serverHost = null;

    private ArrayAdapter<String> adapter = null;

    private volatile Boolean isRunning=true;

    private Thread listenDevices =null;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ListView listView = (ListView) this.findViewById(R.id.listView);
        adapter = new ArrayAdapter(
                this,
                R.layout.item,
                deviceList);
        listView.setAdapter(adapter);
         final mainActivity mainActivity = this;
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String result=((TextView)view).getText().toString();
                Intent intent = new Intent(mainActivity, ConnectingActivity.class);
                intent.putExtra("ip",result);
                startActivity(intent);
            }
        });
        deviceReceive();
    }

    @Override
    protected void onStart() {
        System.out.println("开始监听");
        super.onStart();
        getDevicesList(null);
    }

    @Override
    protected void onStop() {
        System.out.println("停止监听");
        super.onStop();
    }

    public void getDevicesList(@Nullable View view) {
        if (deviceList.size() > 0) {
            deviceList.clear();
            adapter.notifyDataSetChanged();
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                try (DatagramSocket datagramSocketSend = new DatagramSocket(65001);) {
                    InetAddress inetAddress = InetAddress.getByName(BROADCAST_IP);
                    byte[] data = "echo".getBytes();
                    DatagramPacket datagramPacket = new DatagramPacket(data, data.length, inetAddress, 10011);
                    datagramSocketSend.setBroadcast(true);
                    datagramSocketSend.send(datagramPacket);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    public void deviceReceive() {
        listenDevices = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
// 创建接收数据报套接字并将其绑定到本地主机上的指定端口
                    DatagramSocket datagramSocket = new DatagramSocket(10012);
                    while (!Thread.currentThread().isInterrupted()) {
                        try {
                            byte[] buf = new byte[1024];
                            final DatagramPacket datagramPacket = new DatagramPacket(buf, buf.length);
                            datagramSocket.receive(datagramPacket);

                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    serverHost = datagramPacket.getAddress().getHostAddress();
                                    final String message = new String(datagramPacket.getData(), 0, datagramPacket.getLength())
                                            + " from " + datagramPacket.getAddress().getHostAddress() + ":" + datagramPacket.getPort();
                                    String device = message.split("from ")[1].replace(":10011", "").trim();
                                    if (!deviceList.contains(device)){
                                        deviceList.add(device);
                                    }
                                    adapter.notifyDataSetChanged();
                                }
                            });
                            Thread.sleep(500);
                        } catch (InterruptedException e) {
                            System.out.println("接收到中断操作请求，监听被打断");

                            break;
                        }
                    }
                    datagramSocket.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        listenDevices.start();
    }

    @Override
    protected void onDestroy() {
        listenDevices.interrupt();
        super.onDestroy();
    }
}
